<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="120px">
      <el-row>
        <el-form-item label="日期:">
          <el-radio-group v-model="dayRadio">
            <el-radio-button :label="1" @change="TodayData(0)">今天</el-radio-button>
            <el-radio-button :label="2" @change="TodayData(-2)">昨天</el-radio-button>
            <el-radio-button :label="3" @change="TodayData(-6)">全部</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="dateRange"
            :disabled-date="disabledDate"
            end-placeholder="结束日期"
            range-separator="-"
            start-placeholder="开始日期"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            @focus="handleFocus"
            :clearable="false"
            @calendar-change="handleChange"
            @change="handleQuery"
          />
        </el-form-item>
      </el-row>
      <el-form-item label="外部商户号" prop="outMerchantNo">
        <el-input style="width: 230px" v-model="queryParams.outMerchantNo" clearable placeholder="请输入外部商户号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商户名称" prop="merchantName">
        <el-input style="width: 230px" v-model="queryParams.merchantName" clearable placeholder="请输入商户名称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商户简称" prop="shortName">
        <el-input style="width: 230px" v-model="queryParams.shortName" clearable placeholder="请输入商户简称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属银联机构号" prop="unionPayInsNo">
        <el-input style="width: 230px" v-model="queryParams.unionPayInsNo" clearable placeholder="请输入所属银联机构号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="银联商户号" prop="unionPayMrchntNo">
        <el-input style="width: 230px" v-model="queryParams.unionPayMrchntNo" clearable placeholder="请输入银联商户号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="执照编号" prop="licenceNo">
        <el-input style="width: 230px" v-model="queryParams.licenceNo" clearable placeholder="请输入执照编号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="经营范围" prop="manageScope">
        <el-input style="width: 230px" v-model="queryParams.manageScope" clearable placeholder="请输入经营范围" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="法人名称" prop="lepCertName">
        <el-input style="width: 230px" v-model="queryParams.lepCertName" clearable placeholder="请输入法人名称" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="法人证件编号" prop="lepCertNo">
        <el-input style="width: 230px" v-model="queryParams.lepCertNo" clearable placeholder="请输入法人证件编号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input style="width: 230px" v-model="queryParams.contactName" clearable placeholder="请输入联系人" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系人手机号" prop="contactMobile">
        <el-input style="width: 230px" v-model="queryParams.contactMobile" clearable placeholder="请输入联系人手机号" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="注册资金" prop="registeredCapital">
        <el-input style="width: 230px" v-model="queryParams.registeredCapital" clearable placeholder="请输入注册资金" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb20 mt20">
      <el-col :span="1.5">
        <el-button v-hasPermi="['laiqianle:register:add']" icon="Plus" plain type="primary" @click="handleAdd"> 新增 </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['laiqianle:register:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate">修改 </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-tabs v-model="queryParams.auditStatus" class="demo-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="今日审件" name="5" />
      <el-tab-pane label="昨日审件" name="6" />
      <el-tab-pane label="待审核" name="1" />
      <el-tab-pane label="审核通过" name="2" />
      <el-tab-pane label="审核拒绝" name="3" />
      <el-tab-pane label="提交失败" name="4" />
    </el-tabs>
    <el-table v-loading="loading" :data="registerList" @selection-change="handleSelectionChange">
      <el-table-column align="center" fixed="left" type="selection" width="55" />
      <el-table-column align="center" fixed="left" label="合伙人" prop="agentName" />
      <el-table-column align="center" fixed="left" label="外部商户号" prop="outMerchantNo" width="190">
        <template #default="scope">
          <p>
            {{ scope.row.outMerchantNo }}
          </p>
          <el-button type="text" @click="copy(scope.row.outMerchantNo)">拷贝商户号</el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="left" label="商户编码" prop="laiqinale_sn">
        <template #default="scope">
          <p>
            {{ scope.row.laiqinale_sn }}
          </p>
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="left" label="收单机构商户号" prop="merlqianleid" width="190">
        <template #default="scope">
          <p>
            {{ scope.row.merlqianleid }}
          </p>
          <el-button type="text" @click="copy(scope.row.outMerchantNo)">拷贝商户号</el-button>
        </template>
      </el-table-column>
      <!-- :1.企业商户2.个体工商户3.小微商户-->
      <el-table-column align="center" fixed="left" label="入网类型" prop="netType" width="110">
        <template #default="scope">
          <dict-tag :options="laiqianle_register_type" :value="scope.row.netType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="电子签约" prop="eSign">
        <template #default="scope">
          {{ scope.row.isUseElecAgreement === 'true' || scope.row.isUseElecAgreement === true ? '是' : '否' }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="商户名称" prop="merchantName" width="200">
        <template #default="scope">
          <p> {{ scope.row.merchantName }} </p>
          <br />
          <p v-if="scope.row.auditStatus == 3 || scope.row.isSubmit == 1" style="color: red"> {{ scope.row.auditResult }} </p>
        </template>
      </el-table-column>

      <!--      <el-table-column align="center" label="执照类型" prop="licenceType">
        <template #default="scope">
          <dict-tag :options="laiqianle_license_type" :value="scope.row.licenceType" />
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="商户简称" prop="shortName" />
      <el-table-column align="center" label="法人名称" prop="lepCertName" />
      <!--      <el-table-column align="center" label="证件类型" prop="lepCertType">-->
      <!--        <template #default="scope">-->
      <!--          <dict-tag :options="laiqianle_card_type" :value="scope.row.lepCertType" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column align="center" label="联系人" prop="contactName" />-->
      <!--      <el-table-column align="center" label="联系人手机号" prop="contactMobile" width="110" />-->
      <el-table-column align="center" label="备注" prop="remarks" />
      <el-table-column align="center" fixed="right" label="审核状态" prop="auditStatus">
        <template #default="scope">
          <dict-tag :options="audit_status" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="商户状态" prop="merchantStatus">
        <template #default="scope">
          <dict-tag :options="merchant_terminal_status" :value="scope.row.merchantStatus" />
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="添加时间" prop="createTime" />
      <el-table-column align="center" fixed="right" label="修改时间" prop="updateTime" />

      <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="100">
        <template #default="scope">
          <el-button v-hasPermi="['laiqianle:register:edit']" icon="Edit" type="text" @click="handleUpdate(scope.row)"> 修改 </el-button>
          <!--          <el-button icon="upload" type="text" @click="handleReport(scope.row)">上报机构</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />

    <!-- 添加或修改来钱乐商户注册对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="500px">
      <el-form ref="registerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="外部商户号" prop="outMerchantNo">
          <el-input v-model="form.outMerchantNo" placeholder="请输入外部商户号" />
        </el-form-item>
        <el-form-item label="微信服务商号" prop="wxServiceNo">
          <el-input v-model="form.wxServiceNo" placeholder="请输入微信服务商号" />
        </el-form-item>
        <el-form-item label="微信服务商名称" prop="wxServiceName">
          <el-input v-model="form.wxServiceName" placeholder="请输入微信服务商名称" />
        </el-form-item>
        <el-form-item label="微信AppId" prop="wxAppId">
          <el-input v-model="form.wxAppId" placeholder="请输入微信AppId" />
        </el-form-item>
        <el-form-item label="支付宝PID" prop="aliPId">
          <el-input v-model="form.aliPId" placeholder="请输入支付宝PID" />
        </el-form-item>
        <el-form-item label="支付宝服务商名称" prop="aliServiceName">
          <el-input v-model="form.aliServiceName" placeholder="请输入支付宝服务商名称" />
        </el-form-item>
        <el-form-item label="商户名称" prop="merchantName">
          <el-input v-model="form.merchantName" placeholder="请输入商户名称" />
        </el-form-item>
        <el-form-item label="商户简称" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入商户简称" />
        </el-form-item>
        <el-form-item label="是否直联接入:true：是；false：否" prop="isDirectConnect">
          <el-input v-model="form.isDirectConnect" placeholder="请输入是否直联接入:true：是；false：否" />
        </el-form-item>
        <el-form-item label="所属银联机构号" prop="unionPayInsNo">
          <el-input v-model="form.unionPayInsNo" placeholder="请输入所属银联机构号" />
        </el-form-item>
        <el-form-item label="银联商户号" prop="unionPayMrchntNo">
          <el-input v-model="form.unionPayMrchntNo" placeholder="请输入银联商户号" />
        </el-form-item>
        <el-form-item label="执照编号" prop="licenceNo">
          <el-input v-model="form.licenceNo" placeholder="请输入执照编号" />
        </el-form-item>
        <el-form-item label="执照有效期" prop="licenceExpireDate">
          <el-input v-model="form.licenceExpireDate" placeholder="请输入执照有效期" />
        </el-form-item>
        <el-form-item label="经营范围" prop="manageScope">
          <el-input v-model="form.manageScope" placeholder="请输入经营范围" />
        </el-form-item>
        <el-form-item label="法人名称" prop="lepCertName">
          <el-input v-model="form.lepCertName" placeholder="请输入法人名称" />
        </el-form-item>
        <el-form-item label="法人证件编号" prop="lepCertNo">
          <el-input v-model="form.lepCertNo" placeholder="请输入法人证件编号" />
        </el-form-item>
        <el-form-item label="法人证件有效期" prop="lepCertExpireDate">
          <el-input v-model="form.lepCertExpireDate" placeholder="请输入法人证件有效期" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系人手机号" prop="contactMobile">
          <el-input v-model="form.contactMobile" placeholder="请输入联系人手机号" />
        </el-form-item>
        <el-form-item label="注册资金" prop="registeredCapital">
          <el-input v-model="form.registeredCapital" placeholder="请输入注册资金" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入内容" type="textarea" />
        </el-form-item>
        <el-form-item label="" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="Register" setup>
  import useClipboard from 'vue-clipboard3';
  import { addRegister, businessTypeList, listRegister, reportOrgOne, updateRegister } from '@/api/laiqianle/register';
  import { getCurrentInstance, reactive, ref, toRefs } from 'vue';
  import { useDict } from '@/utils/dict';
  import { useRouter } from 'vue-router';
  import { TodayDataTimeUtils } from '@/utils/dateUtils';
  import { dayjs } from 'element-plus';

  const { proxy } = getCurrentInstance();

  // 字典 laiqianle_register_type 入网类型  laiqianle_card_type 证件类型  laiqianle_license_type 营业执照类型
  const { laiqianle_register_type, laiqianle_card_type, laiqianle_license_type, audit_status, merchant_terminal_status } = useDict(
    'laiqianle_register_type',
    'laiqianle_card_type',
    'laiqianle_license_type',
    'audit_status',
    'merchant_terminal_status',
  );

  const outMerchantNo = ref([]);
  const registerList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');
  const dateRange = ref([dayjs().startOf('date').format('YYYY-MM-DD HH:mm:ss'), dayjs(`${new Date()}`).format('YYYY-MM-DD HH:mm:ss')]);
  const pickerMinDate = ref(null);
  const dayRadio = ref(1);
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      outMerchantNo: null,
      netType: null,
      wxServiceNo: null,
      wxServiceName: null,
      wxAppId: null,
      aliPId: null,
      aliServiceName: null,
      merchantName: null,
      shortName: null,
      isDirectConnect: null,
      unionPayInsNo: null,
      unionPayMrchntNo: null,
      licenceType: null,
      licenceNo: null,
      licenceExpireDate: null,
      manageType: null,
      manageScope: null,
      lepCertName: null,
      lepCertType: null,
      lepCertNo: null,
      lepCertExpireDate: null,
      contactName: null,
      contactMobile: null,
      registeredCapital: null,
      remarks: null,
      auditStatus: '5',
      merchantStatus: null,
      isSubmit: 0,
      params: {
        startTime: '',
        endTime: '',
      },
    },
    rules: {},
  });
  const { queryParams, form, rules } = toRefs(data);

  // 经营类型
  interface BusinessType {
    id: number;
    name: string;
    code: string;
    pcode: string;
    children: BusinessType[];
    [key: string]: any;
  }

  const businessTypeOptions = ref<BusinessType[]>([]);
  const getBusinessTypeList = async () => {
    const { data } = await businessTypeList();
    businessTypeOptions.value = data;
  };

  // 过滤
  const handleFilter = (list, value, code) => {
    const result = list.filter((item) => item[code] === value);
    return result.length ? result[0]?.name || result[0]?.bankName : '';
  };

  /** 查询来钱乐商户注册列表 */
  function getList() {
    loading.value = true;
    queryParams.value.params.startTime = dateRange.value[0];
    queryParams.value.params.endTime = dateRange.value[1];
    let params = JSON.parse(JSON.stringify(queryParams.value));
    if (params.auditStatus === '4') {
      params.auditStatus = null;
      params.isSubmit = 1;
    } else {
      params.isSubmit = 0;
    }
    // 今日审核查询条件新增
    if (params.auditStatus === '5' || params.auditStatus === '6') {
      delete params.params.startTime;
      delete params.params.endTime;
      params.params.startUpdateTime =
        params.auditStatus === '5' ? dayjs().startOf('date').format('YYYY-MM-DD HH:mm:ss') : dayjs().subtract(1, 'day').startOf('date').format('YYYY-MM-DD HH:mm:ss');
      params.params.endUpdateTime =
        params.auditStatus === '5' ? dayjs().endOf('date').format('YYYY-MM-DD HH:mm:ss') : dayjs().subtract(1, 'day').endOf('date').format('YYYY-MM-DD HH:mm:ss');
      params.auditStatus = 2;
      params.merchantStatus = 2;
    }
    listRegister(queryParams.value).then((response) => {
      registerList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
  function handleTabClick(e) {
    // console.log('handleTabClick', e.props.name);
    queryParams.value.auditStatus = e.props.name;
    queryParams.value.pageNum = 1;
    getList();
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      id: null,
      outMerchantNo: null,
      netType: null,
      wxServiceNo: null,
      wxServiceName: null,
      wxAppId: null,
      aliPId: null,
      aliServiceName: null,
      merchantName: null,
      shortName: null,
      isDirectConnect: null,
      unionPayInsNo: null,
      unionPayMrchntNo: null,
      licenceType: null,
      licenceNo: null,
      licenceExpireDate: null,
      manageType: null,
      manageScope: null,
      lepCertName: null,
      lepCertType: null,
      lepCertNo: null,
      lepCertExpireDate: null,
      contactName: null,
      contactMobile: null,
      registeredCapital: null,
      remarks: null,
      auditStatus: '0',
      merchantStatus: '0',
      updateBy: null,
      updateTime: null,
      delFlag: null,
      createBy: null,
      createTime: null,
    };
    proxy.resetForm('registerRef');
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm('queryRef');
    dateRange.value = [dayjs().startOf('date').format('YYYY-MM-DD HH:mm:ss'), dayjs(`${new Date()}`).format('YYYY-MM-DD HH:mm:ss')];
    dayRadio.value = 1;
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    outMerchantNo.value = selection.map((item) => item.outMerchantNo);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    // reset();
    // open.value = true;
    // title.value = '添加来钱乐商户注册';
    proxy.$router.push('laiqianle/register/add');
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    // reset();
    const _id = row.id || ids.value[0];
    const _outMerchantNo = row.outMerchantNo || outMerchantNo.value[0];
    const _merlqianleid = row.merlqianleid;
    const _merchantName = row.merchantName;
    const _auditStatus = row.auditStatus;
    proxy.$router.push(
      `laiqianle/register/detail?id=${_id}&outMerchantNo=${_outMerchantNo}&merlqianleid=${_merlqianleid}&merchantName=${_merchantName}&auditStatus=${_auditStatus}`,
    );
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs['registerRef'].validate((valid) => {
      if (valid) {
        if (form.value['id'] != null) {
          updateRegister(form.value).then(() => {
            proxy.$modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addRegister(form.value).then(() => {
            proxy.$modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 上报机构 */
  const handleReport = (row) => {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm('是否确认上报商户注册编号为"' + _ids + '"的数据项？')
      .then(function () {
        return reportOrgOne(row.outMerchantNo).then((res) => {
          getList();
          proxy.$modal.msgSuccess(res.msg);
        });
      })
      .catch(() => {});
  };

  const router = useRouter();
  queryParams.value.outMerchantNo = router.currentRoute.value.query.outMerchantNo ?? null;

  // getList();
  getBusinessTypeList();

  const { toClipboard } = useClipboard();

  const copy = async (outMerchantNo) => {
    try {
      await toClipboard(outMerchantNo);
      console.log('Copied to clipboard');
    } catch (e) {
      console.error(e);
    }
  };
  function TodayData(day) {
    // today.value = TodayDataTimeUtils(day);
    if (day === 0) {
      dayRadio.value = 1;
      dateRange.value = [dayjs().startOf('date').format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss')];
    } else if (day === -2) {
      // 昨天
      dayRadio.value = 2;
      dateRange.value = [
        dayjs().subtract(1, 'day').startOf('date').format('YYYY-MM-DD HH:mm:ss'),
        dayjs().subtract(1, 'day').endOf('date').format('YYYY-MM-DD HH:mm:ss'),
      ];
    } else if (day === -6) {
      // 全部
      dayRadio.value = 3;
      dateRange.value = [null, null];
    }
    getList();
  }

  function handleChange(data) {
    console.log(data);
    const [pointDay] = data;
    pickerMinDate.value = pointDay;
  }

  //取值方法
  function handleFocus() {
    pickerMinDate.value = null;
  }

  function disabledDate(time) {
    if (!pickerMinDate.value) {
      return false;
    }
    let timeRange = 30;
    const con1 = new Date(pickerMinDate.value).getTime() - timeRange * 24 * 60 * 60 * 1000;
    const con2 = new Date(pickerMinDate.value).getTime() + timeRange * 24 * 60 * 60 * 1000;
    return time < con1 || time > con2;
  }
  TodayData(0);
</script>
<style lang="scss" scoped></style>
